<template>
  <div>
    <div class="topSearchBox">
      <el-input v-model="orgQueryParams.keyword" clearable placeholder="输入关键字查询" size="small"/>
      <el-button type="primary" @click="handleSearch">查 询</el-button>
    </div>
    <el-tree
      ref="orgTree"
      class="filter-tree"
      :style="{'height': treeHeight - 70 + 'px','overflow': 'auto'}"
      accordion
      highlight-current
      :data="treeData"
      :props="defaultProps"
      :load="loadNode"
      current-node-key="id"
      lazy
      node-key="id"
      :filter-node-method="filterNode"
      @node-click="treeNodeClick"
    >
      <template slot-scope="{node,data}">
        <span :title="data.name" class="span-ellipsis">{{ data.name }}</span>
      </template>
    </el-tree>
  </div>
</template>
<script>
import { organizationTree } from '@/api/userManage'
export default {
  props: {
    treeHeight: {
      type: [Number, String],
      require: false,
      default: () => 0
    }
  },
  name: 'OrgTree',
  data () {
    return {
      orgQueryParams: {
        parent: '',
        keyword: undefined
      },
      treeData: [],
      defaultProps: {
        children: 'sub',
        label: 'name',
        isLeaf: 'leafNode'
      }
    }
  },
  methods: {
    handleSearch () {
      this.getOrgLazyloadTree('')
    },
    loadNode (node, resolve) {
      if (node.level === 0) {
        return this.getOrgLazyloadTree('')
      }
      if (node.level >= 1) this.getOrgLazyloadTree(node.data.id, resolve)
    },
    // 获取列表数据
    async getOrgLazyloadTree (id, resolve) {
      this.orgQueryParams.parent = id
      const res = await organizationTree(this.orgQueryParams)
      if (res.code !== 'success') return
      console.log('组织机构', res)
      res.data.forEach(v => {
        v.leafNode = v.childNum <= 0
      })
      if (id === '') {
        if (res.data.length > 0) {
          this.$emit('input', res.data[0])
          this.$nextTick(() => {
            this.$refs.orgTree.setCurrentKey(res.data[0].id)
          })
        }
        return (this.treeData = res.data)
      }
      return resolve(res.data) // 最顶层数据渲染为region
    },
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    treeNodeClick (node) {
      this.$emit('input', node)
    }
  }
}
</script>
<style scoped lang="scss" >
.filter-tree{
  margin-top: 20px;
  font-size: 14px;
}
::v-deep .el-tree-node__content{
  height: 35px;
}
.span-ellipsis{
  display: block;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.topSearchBox{
  display: flex;
  .el-input{
    margin-right: 10px;
  }
}
</style>
